/* eslint-disable react-hooks/exhaustive-deps */
"use client";
import React, { useState, useEffect } from "react";
import type { BreadcrumbProps } from "antd";
import { Button, Skeleton, Alert, Empty, Pagination, Breadcrumb } from "antd";
import Image from "next/image";
import { useCategories } from "@/hooks/useCategories";
import { useRouter, useSearchParams } from "next/navigation";
import { createStyles } from "antd-style";
import SearchBar from "@/components/SearchBar";
import { userCenterGet2 } from "@/apis";

// 定义分类按钮类型
interface CategoryButton {
  key: string;
  label: string;
}

interface CenterProductModel {
  productId?: number;
  productName?: string;
  brand?: string;
  model?: string;
  mainPhotoes?: Array<{
    category: string | null;
    attachmentName: string;
    attachmentAddress: string;
  }>;
  gradeName?: string;
  grade?: string;
  coreTarget?: string;
  inspectionStatus?: number;
}

interface HotRecProps {
  product?: CenterProductModel;
}

// 自定义按钮样式
const useStyle = createStyles(({ prefixCls, css }) => ({
  categoryButtonGroup: css`
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  `,
  categoryButton: css`
    position: relative;
    border-radius: 4px;
    transition: all 0.3s ease;

    &.${prefixCls}-btn {
      background: #fff;
      color: #333;
      border: 1px solid #d9d9d9;

      &:hover:not([disabled]) {
        border-color: #2570ff;
        color: #2570ff;
        background: #f0f7ff;
      }
    }
  `,
  categoryButtonActive: css`
    &.${prefixCls}-btn {
      background: linear-gradient(135deg, #2570ff, #1890ff);
      color: #fff;
      border: none;
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
      &:hover:not([disabled]) {
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
        background: linear-gradient(135deg, #1890ff, #096dd9);
      }
    }
  `,
}));

export default function HotRec({}: HotRecProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { styles } = useStyle();
  const {
    categories,
    loading: categoryLoading,
    error: categoryError,
  } = useCategories();

  // 从 URL 查询参数初始化状态
  const [current, setCurrent] = useState(
    () => searchParams.get("condition.category") || "全部"
  );
  const [currentPage, setCurrentPage] = useState(() =>
    parseInt(searchParams.get("condition.page") || "1", 10)
  );
  const [keyword, setKeyword] = useState(
    () => searchParams.get("condition.keyword") || ""
  );
  const [totalItems, setTotalItems] = useState(0);
  const [pageSize] = useState(20);
  const [imgErrorMap, setImgErrorMap] = useState<Record<string, boolean>>({});
  const [productList, setProductList] = useState<CenterProductModel[]>([]);
  const [productLoading, setProductLoading] = useState(false);
  const [productError, setProductError] = useState<string | null>(null);

  const getCategoryButtons = (): CategoryButton[] => {
    const allCategory: CategoryButton = { key: "全部", label: "全部" };
    return [
      allCategory,
      ...(categories || []).map((category) => ({
        key: category.key || `category-${Date.now()}`,
        label: category.label || "未知分类",
      })),
    ];
  };

  const handleCategoryClick = (categoryKey: string) => {
    setCurrent(categoryKey);
    setCurrentPage(1);
    // 更新 URL 以反映分类变化
    const params = new URLSearchParams(searchParams);
    params.set("condition.category", categoryKey === "全部" ? "" : categoryKey);
    params.set("condition.page", "1");
    router.push(`/products?${params.toString()}`);
  };

  const getBreadcrumbItems = (): BreadcrumbProps["items"] => {
    return [
      {
        title: (
          <span onClick={() => router.push("/")} className="cursor-pointer">
            首页
          </span>
        ),
        key: "home",
      },
      {
        title: (
          <span
            onClick={() => router.push("/products")}
            className="cursor-pointer"
          >
            产品列表
          </span>
        ),
        key: "products",
      },
      {
        title: current,
        key: `category-${current}`,
        isCurrent: true,
      },
    ];
  };

  const getFullImageUrl = (relativePath: string) => {
    if (!relativePath) return "/images/default-product.png";
    if (relativePath.startsWith("http")) return relativePath;
    const ossBaseUrl = "https://oss.tz-group.com/";
    const cleanPath = relativePath.startsWith("/")
      ? relativePath.slice(1)
      : relativePath;
    return `${ossBaseUrl}${cleanPath}`;
  };

  const handleImageError = (productId: string | number) => {
    setImgErrorMap((prev) => ({ ...prev, [productId]: true }));
  };

  const fetchProducts = async (
    categoryKey: string,
    page: number,
    searchKeyword: string
  ) => {
    setProductLoading(true);
    setProductError(null);
    try {
      const apiCategory = categoryKey.startsWith("sub-")
        ? categoryKey.split("-").slice(2).join("-")
        : categoryKey;
      const params = {
        page: page,
        size: pageSize,
        isPopular: false,
        keyword: searchKeyword,
        category: categoryKey === "全部" ? "" : apiCategory,
      };
      const queryString = new URLSearchParams(params).toString();
      const response = await userCenterGet2({
        url: `/user_center/product?${queryString}`,
        baseURL: "/api/proxy",
      });
      setProductList(response?.data?.data?.data || []);
      setTotalItems(response?.data?.data?.total || 0);
    } catch (err) {
      setProductError("网络异常，无法加载产品数据");
    } finally {
      setProductLoading(false);
    }
  };

  useEffect(() => {
    if (!categoryLoading && !categoryError) {
      fetchProducts(current, currentPage, keyword);
    }
  }, [current, currentPage, keyword, categoryLoading, categoryError]);

  // 同步 URL 查询参数变化
  useEffect(() => {
    const newKeyword = searchParams.get("condition.keyword") || "";
    const newCategory = searchParams.get("condition.category") || "全部";
    const newPage = parseInt(searchParams.get("condition.page") || "1", 10);

    setKeyword(newKeyword);
    setCurrent(newCategory);
    setCurrentPage(newPage);
  }, [searchParams]);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    // 更新 URL 以反映页面变化
    const params = new URLSearchParams(searchParams);
    params.set("condition.page", page.toString());
    router.push(`/products?${params.toString()}`);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  // 高亮搜索关键词的组件
  const HighlightText = ({
    text,
    keyword,
  }: {
    text: string;
    keyword: string;
  }) => {
    if (!keyword.trim()) return <span>{text}</span>;
    const regex = new RegExp(`(${keyword})`, "gi");
    const parts = text.split(regex);
    return (
      <span>
        {parts.map((part, index) =>
          regex.test(part) ? (
            <mark
              key={index}
              className="px-1 rounded font-bold text-lg text-[#1677FF]"
            >
              {part}
            </mark>
          ) : (
            <span key={index}>{part}</span>
          )
        )}
      </span>
    );
  };

  const renderProductCard = (product: CenterProductModel) => {
    const productId = product.productId?.toString() || "unknown";
    const productImg = product.mainPhotoes?.[0]?.attachmentAddress;

    const fullImageUrl = getFullImageUrl(productImg || "");
    const hasError = imgErrorMap[productId];
    const currentGrade = product.grade || "A";
    const allGrades = [
      { grade: "A", label: "A", color: "#027F3F" },
      { grade: "B", label: "B", color: "#68D300" },
      { grade: "C", label: "C", color: "#FFB422" },
      { grade: "D", label: "D", color: "#FF8738" },
    ];

    return (
      <div
        key={productId}
        className="bg-white shadow-md p-4 flex cursor-pointer hover:shadow-lg transition-shadow duration-300 border-[#E0E0E0]"
        onClick={() => {
          router.push(`/products/${productId}`);
        }}
      >
        <div className="relative w-[180px] h-[180px] flex-shrink-0">
          <Image
            src={hasError ? "/images/default-product.png" : fullImageUrl}
            alt={product.productName || "产品图片"}
            width={180}
            height={180}
            onError={() => handleImageError(productId)}
            className="object-cover"
          />
        </div>
        <div className="text-sm flex-1 ml-4">
          <h2 className="flex justify-between">
            <div className="text-sm font-bold text-[#2F2F2F] line-clamp-2">
              <HighlightText
                text={product.productName || "未命名产品"}
                keyword={keyword}
              />
            </div>
            <div className="text-[#2CD39C] px-2 border border-[#33D598] bg-[#F2FFF4]">
              <HighlightText
                text={product.coreTarget || "无目标"}
                keyword={keyword}
              />
            </div>
          </h2>
          <p className="text-[#091423] mb-1">
            品牌：
            <HighlightText
              text={product.brand || "未知品牌"}
              keyword={keyword}
            />
          </p>
          <p className="text-[#091423] mb-1">
            产地：
            <HighlightText text={product.model || "无规格"} keyword={keyword} />
          </p>
          <p className="text-[#095CDC] mb-2">
            <HighlightText
              text={product.gradeName || "等级认证"}
              keyword={keyword}
            />
          </p>
          <div className="flex space-x-2 mt-3">
            {allGrades.map((gradeInfo) => (
              <span
                key={gradeInfo.grade}
                className={`px-3 py-1 text-white rounded transform skew-x-22 text-lg font-medium transition-all duration-200 ${
                  currentGrade === gradeInfo.grade
                    ? "h-8 scale-110 shadow-md"
                    : "h-6 opacity-80"
                }`}
                style={{
                  backgroundColor: gradeInfo.color,
                  lineHeight:
                    currentGrade === gradeInfo.grade ? "24px" : "18px",
                }}
              >
                <span className="transform -skew-x-22 inline-block">
                  {gradeInfo.label}
                </span>
              </span>
            ))}
          </div>
        </div>
      </div>
    );
  };

  const renderProducts = () => {
    if (productLoading) {
      return Array(pageSize)
        .fill(0)
        .map((_, idx) => (
          <div key={idx} className="bg-white shadow-md p-4 flex">
            <Skeleton.Image
              style={{ width: 140, height: 140 }}
              className="mr-6"
            />
            <div className="flex-1 space-y-2">
              <Skeleton active paragraph={{ rows: 1, width: "80%" }} />
              <Skeleton active paragraph={{ rows: 2, width: "100%" }} />
              <Skeleton active paragraph={{ rows: 1, width: "60%" }} />
              <div className="flex space-x-1 mt-2">
                <Skeleton active className="h-6 w-16 rounded" />
              </div>
            </div>
          </div>
        ));
    }

    if (productError) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Alert message={productError} type="error" showIcon />
        </div>
      );
    }

    if (productList.length === 0) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Empty description="暂无相关产品" />
        </div>
      );
    }

    return productList.map(renderProductCard);
  };

  return (
    <section>
      <div className="container mx-auto mt-2 flex flex-col items-center justify-between h-full">
        {/* 面包屑 */}
        <div className="w-full my-4">
          <Breadcrumb items={getBreadcrumbItems()} separator=">" />
        </div>
        <SearchBar
          width={600}
          targetPath="/products"
          placeholder="热门产品搜索：医用、米、肉桂、水仙"
          clearAfterSearch={false}
        />
        {/* 分类按钮组 */}
        <div className="w-full my-2">
          <div className={styles.categoryButtonGroup}>
            {categoryLoading ? (
              <Skeleton active paragraph={{ rows: 1, width: "200px" }} />
            ) : categoryError ? (
              <Alert
                message={categoryError}
                type="error"
                showIcon
                style={{ width: "auto" }}
              />
            ) : (
              getCategoryButtons().map((button) => (
                <Button
                  key={button.key}
                  onClick={() => handleCategoryClick(button.key)}
                  className={`
                    ${styles.categoryButton} 
                    ${current === button.key ? styles.categoryButtonActive : ""}
                  `}
                  size="middle"
                  disabled={productLoading}
                >
                  {button.label}
                </Button>
              ))
            )}
          </div>
        </div>

        {/* 产品列表 */}
        <div className="w-full grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {renderProducts()}
        </div>

        {/* 分页 */}
        {!productLoading && !productError && productList.length > 0 && (
          <div className="w-full flex justify-center mt-6 mb-4">
            <Pagination
              current={currentPage}
              pageSize={pageSize}
              total={totalItems}
              onChange={handlePageChange}
              showSizeChanger={false}
              showQuickJumper
              showTotal={(total) => `共 ${total} 条`}
              defaultPageSize={20}
              defaultCurrent={1}
            />
          </div>
        )}
      </div>
    </section>
  );
}
